package cn.explink.dop.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;
import org.springframework.stereotype.Repository;

import cn.explink.distributor.framework.CommonCondition;
import cn.explink.dop.entity.vo.ConditionVO;
import cn.explink.dop.enums.pub.EnableEnum;
import cn.explink.eap.core.common.dao.impl.GenericBaseCommonDao;

/**
 *
 * @author songkaojun 2015年3月21日 Test
 */

@Repository("conditionDao")
public class ConditionDao extends GenericBaseCommonDao<CommonCondition, String> {

	public ConditionVO getConditionById(String conditionId) {
		List<ConditionVO> conditionList = new ArrayList<ConditionVO>();
		StringBuffer sql = new StringBuffer("select * from bd_condition where is_enable=").append(EnableEnum.Enable.getValue()).append(" and id='" + conditionId + "'");

		conditionList = super.getJdbcTemplate().query(sql.toString(), new RowMapperResultSetExtractor<ConditionVO>(new ConditionRowMapper()));
		if (conditionList.size() == 1) {
			return conditionList.get(0);
		} else {
			return new ConditionVO();
		}
	}

	/**
	 * 按照实体查询，无分页
	 *
	 * @param baseInfo
	 *            查询实体
	 * @return 查询列表
	 */
	public List<ConditionVO> getPresetConditionList() {
		List<ConditionVO> conditionList = new ArrayList<ConditionVO>();

		StringBuffer sql = new StringBuffer("select * from bd_condition where is_enable=").append(EnableEnum.Enable.getValue()).append(" and distribute_strategy_id='PRESET'");

		conditionList = super.getJdbcTemplate().query(sql.toString(), new RowMapperResultSetExtractor<ConditionVO>(new ConditionRowMapper()));

		return conditionList;
	}

	class ConditionRowMapper implements RowMapper<ConditionVO> {
		@Override
		public ConditionVO mapRow(ResultSet rs, int index) throws SQLException {
			String className = rs.getString("class_name");
			ConditionVO condition = null;
			try {
				condition = (ConditionVO) Class.forName(className).newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			if (condition != null) {
				condition.setId(rs.getString("id"));
				condition.setName(rs.getString("name"));
				condition.setPriority(rs.getInt("priority"));
				condition.setWeight(rs.getInt("weight"));
				condition.setIsEnable(rs.getInt("is_enable"));
				condition.setClassName(className);
			}
			return condition;
		}
	}
}
